package repository;

import org.apache.commons.dbcp.BasicDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabase;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;

import javax.sql.DataSource;

/**
 * Created by jack on 18/5/31.
 */
@Configuration
public class DsConfig {

    @Bean
    public JdbcTemplate jdbctemplate(DataSource dataSource){
        return new JdbcTemplate(dataSource);
    }

    /*dbcp方式配置数据源*/
    @Bean
    public BasicDataSource dbcp_dataSource(){
        BasicDataSource ds = new BasicDataSource();
        ds.setDriverClassName("com.mysql.jdbc.Driver");
        ds.setUrl("jdbc:mysql://localhost:3309/test");
        ds.setUsername("root");
        ds.setPassword("342623");
        ds.setInitialSize(5);
        ds.setMaxActive(10);
        return ds;
    }

    /*在每次请求连接的时候都会创建新连接*/
    @Profile("qa")
    @Bean
    public DataSource jdbc_dataSource(){
        DriverManagerDataSource ds = new DriverManagerDataSource();
        ds.setDriverClassName("com.mysql.jdbc.Driver");
        ds.setUrl("jdbc:mysql://localhost:3309/test");
        ds.setUsername("root");
        ds.setPassword("342623");
        return ds;
    }

    /*嵌入式数据库*/
    @Profile("development")
    @Bean
    public DataSource embeded_dataSource(){
        return new EmbeddedDatabaseBuilder()
                .setType(EmbeddedDatabaseType.H2)
                .addScript("classpath:schema.sql")
                .addScript("classpath:test-data.sql")
                .build();
    }

}
